<template>
    <div class="main">
        <el-form :rules="rules" ref="loginForm" :model="loginForm" class="loginContainer">
            <h3 class="loginTitle" style="margin-bottom:20px">
                登录
            </h3>
            <el-form-item prop="username">
                <el-input type="text" v-model="loginForm.username" placeholder="请输入账号">
                </el-input>
            </el-form-item>
            <el-form-item prop="password">
                <el-input type="password" v-model="loginForm.password" placeholder="请输入密码">
                </el-input>
            </el-form-item>
            <div class="wrapper">
                <el-row :gutter="20">
                    <el-col :span="16">
                        <el-input v-model="ruleForm.code" placeholder="请输入验证码"></el-input>
                    </el-col>
                    <el-col :span="8" class="captcha-column">
                        <span @click="refreshCode" class="captcha-refresh" style="cursor: pointer; margin-left:-15px">
                            <s-identify :identifyCode="identifyCode"></s-identify>
                        </span>
                    </el-col>
                </el-row>
            </div>
            <el-radio v-model="radio" label="1" style="margin-top: 15px">用户</el-radio>
            <el-radio v-model="radio" label="2" style="margin-bottom: 15px">管理员</el-radio>

            <el-button type="primary" style="width:100%;margin-bottom: 15px;" @click="submitLogin" @keyup.enter="keyDown"
            >登录</el-button>
            <el-button type="text" style="margin-left: 30%;" @click="submitRegister">暂未有账号?前往注册</el-button>
            
        </el-form>
    </div>
</template>

<script>
import SIdentify from "@/components/ValidCode.vue";
import axios from 'axios'
axios.defaults.baseURL = '/api'
export default {
    name: "Login",
    components: {
        SIdentify
    },
    data() {
        return {

            // 图片验证码
            identifyCode: "",
            // 验证码规则
            identifyCodes: "3456789ABCDEFGHGKMNPQRSTUVWXY",
            ruleForm: {
                code: "",
            },
            captchaUrl: "",
            loginForm: {
                username: "",
                password: "",
            },
            checked: true,
            rules: {
                username: [{ required: true, message: "请输入账号", trigger: "blur" }],
                password: [{ required: true, message: "请输入密码", trigger: "blur" }],
                code: [{ required: true, message: "请输入验证码", trigger: "blur" }],
            },

            radio: '1'

        }
    },
    methods: {
        submitLogin() {
            if (this.radio == '2') {
                this.$refs.loginForm.validate((valid) => {
                    if (this.ruleForm.code.toUpperCase() === this.identifyCode.toUpperCase()) {
                        if (valid) {
                            axios.get("/admin/user", {
                                params: {
                                    username: this.loginForm.username,
                                    password: this.loginForm.password
                                }
                            }).then(result => {
                                if (result.data.msg == "success") {
                                    const adminToken = result.data.data;
                                    sessionStorage.setItem('adminToken', adminToken);
                                    this.$router.push({ name: "userAccount" });
                                } else {
                                    this.$message({
                                        message: "账号或密码错误！！！",
                                        type: "error",
                                    });
                                }
                            })
                        } else {
                            return false;
                        }
                    } else {
                        this.$message({
                            message: "请输入正确的验证码！！！",
                            type: "warning",
                        });
                        // 如果输入的验证码不对，那么就在警告后，切换成新的验证码
                        this.refreshCode();
                    }
                });
            }
            else {
                this.$refs.loginForm.validate((valid) => {
                    if (this.ruleForm.code.toUpperCase() === this.identifyCode.toUpperCase()) {
                        if (valid) {
                            axios.get("/user/login", {
                                params: {
                                    username: this.loginForm.username,
                                    password: this.loginForm.password
                                }
                            }).then(result => {
                                if (result.data.data != null) {
                                    const token = result.data.data;
                                    sessionStorage.setItem('token', token); // 存储 token
                                    this.$router.push({ name: "home" });
                                } else {
                                    this.$message({
                                        message: "账号或密码错误！！！",
                                        type: "error",
                                    });
                                }
                            })
                        } else {
                            return false;
                        }
                    } else {
                        this.$message({
                            message: "请输入正确的验证码！！！",
                            type: "warning",
                        });
                        // 如果输入的验证码不对，那么就在警告后，切换成新的验证码
                        this.refreshCode();
                    }
                });

            }

        },
        submitRegister() {
            this.$router.push({ name: "register" });
        },
        keyDown(e){
          //如果是回车则执行登录方法
          if(e.keyCode == 13){
            //需要执行的登录方法
            this.submitLogin();
          }
        },
        // 切换验证码
        refreshCode() {
            this.identifyCode = "";
            this.makeCode(this.identifyCodes, 4);
        },
        makeCode(o, l) {
            for (let i = 0; i < l; i++) {
                this.identifyCode +=
                    this.identifyCodes[
                    Math.floor(Math.random() * this.identifyCodes.length)
                    ];
            }
        }

    },
    mounted() {
        //进入页面则刷新验证码图片
        this.refreshCode();
        //绑定事件
        window.addEventListener('keydown',this.keyDown);
    },
    //销毁事件
    destroyed(){
        window.removeEventListener('keydown',this.keyDown,false);
    }
}
</script>

<style scoped>
.loginContainer {
    border-radius: 15px;
    background-clip: padding-box;
    margin: 180px auto;
    width: 350px;
    padding: 15px 35px 15px 35px;
    background: aliceblue;
}

.captcha-refresh {
    /* 添加一些样式来确保点击区域足够大，不影响图片的显示 */
    display: inline-block;
}

.main {

    width: 100%;
    height: 100vh;
    background-image: url("/src/assets/background.jpg");
    background-size: 100% 100%;
    position: absolute;
}
</style>
